package pkg

import (
	"context"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"log"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
)

const (
	AppID = "wxd82cf42e3b0aff22" // 替换为你的微信应用ID
	MchID = "1674186447"         // 替换为你的商户ID
	//ApiKey    = "-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDgw06UCFbhdWf9 iHH2sry3xRRvopYtSJT3jCCdtYYNEmDvyX9UlhYO+ZPECpUKaBDs3gPqtUMpCzzs u7R2vgg9a2mAFGJhAUMWZkS8e1P17DNmwnByZLbCsYGKPgbK8anzjNrvUSq9PVge Cg4a5j0S2kqzIH6E1f1pW/y8vVxWAfe+mDyVjHmfPJAHaoe6pVXXVpmQDO83Aryy GwZRLEMgvaaPM4NOgl2NeD6fzuRih/BdS2aipFtgmZ4il0rOsHtWU/WEXCZ+FvMX 9BCzktWEpvV4GyK/LsB+uewifDiq5eB8ubWVrnOqL0hmfp+vcqPLyIVefyLTsPGb spnNy1SvAgMBAAECggEAcS+JY5yre9Au9QsAMPajeHvDpdAfhmBVvC+RwTnHbs/B hx9Wgtct9o6SbhfSJDJxy4amPEzZrFKfdKu13lImPh/YOgqJ3EXRbfdESBJnHqG6 5NWn4MN9EaBoFqDTtOFr710QZ5HdTv0UYdQ4dC1btiG9mmUTsXs9qRAMv1Mwq5JS UCeZtaUO39jNdaoVR1rHT3Zxzepkv0IajmNvmDCvr8xrQiLEH/vPtLMJhMjMWERC 5SUH/tMvz3hNLKpBvh5qtcp/CSLd7j6AGPSsP/zZK64uN7DG3l28/zi1uv4Zq07U BmUsM7B5Sykz4S/eCD69Ru3tA/nQoTamYEt2lcMAYQKBgQD51l0Gl9saulpGywcD jFNxI57D4riXSVCDcShn5NfI2nbsFCQcO59Bv0RpeTaB/d6BKddBekOiSuBzySFS mdkc35i7KZTG0T8FZ0PkTnYPplgtr7ZOcvfottNdQqkvWccGCovdYYEVWYmHWroO dWd8umAE8/7lxF/rbJyzNuIBHwKBgQDmTpttnRU0kMlUcOIN+nT+7Rb+b8b0L4Ov Ealyyy3HkWaX3YCesUZyDNdYg8atJUqRDH/Pdf/Zqpegol1CwTlQ+xHZqwY+Hjrl Tymu5jGXVLC8JgL22nxtTXfsF0eQDu1imcLHkvv1EJxURLKN3ABEAu6sMlG5P0Jx xavBtC5qcQKBgCRhIYSfQilfL1wVnjzXByN3Y1v0vJpS86VgKdkPCpjVrvFrcWKn D+ab+lM9ckF1fRvjwtNnAUg1jP9vLyn++w1oRa4jPOXCfGHGCq3I+woGV9q3Nl2w Agdh798poMcjVIa9rGYdF5XLRuptvJ/0WpBf9zFhciF0+d6nHx49hKVTAoGALXSg Wr8hO1HEWuU4yLeBNfuHiUp4gyOJoxkiT6TocTYygJDYXPnyRHpiWncP1IbCs+Q6 qbDJgaWY7bx+GbnXXTNgr4yA2+vNhgrc2EdYzFyL0WbTOPOgkVYz8CYcGsPHeKmO dyN8lT7lDADPGQ6uAr5taxE3bg+dRqVUJBQzARECgYEAqWs27MO+fZpERHuqpK5+ 4Bx3M65n81vIsxBqD5uNFM9OudLnSER6clq+s0sHHbzerKCwvXbPJbKVJzN8bAYd kMH6cL2JzUQfJ6QX2grSh7g9prf0QKMqVXTW3bVLFmgKnpmZaTjYZyvtVhoT6hKi kLUOYU7oZtczZVNJoXNVe+M= -----END PRIVATE KEY-----" // 替换为你的API密钥
	NotifyURL = "https://wxpay.xinxuecheng.cn/wx/pay1"
	// 替换为你的支付结果通知URL
	MchAPIv3Key                = "gCwX9icQtoEWjMrDzOAEer1Ewpf3nBhG"         //v3密钥
	MchCertificateSerialNumber = "501AD7CFF3014433FA20A326E3222EF19E538B2A" //证书序列号；

)

var MchPrivateKey, err = utils.LoadPrivateKeyWithPath("pkg/weixinpay/lss/apiclient_key.pem")

func pay() {
	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	//mchPrivateKey, err: = utils.LoadPrivateKeyWithPath("/pkg/weixinpay/apiclient_key.pem")
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("/pkg/weixinpay/lss/apiclient_key.pem")
	if err != nil {
		fmt.Println("load merchant private key error123:", err)
	}
	ctx := context.Background()
	// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(MchID, MchCertificateSerialNumber, mchPrivateKey, MchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Fatalf("new wechat pay client err:%s", err)
	}
	// 以 Native 支付为例
	svc := native.NativeApiService{Client: client}
	// 发送请求
	resp, result, err := svc.Prepay(ctx,
		native.PrepayRequest{
			Appid:       core.String("wxd678efh567hg6787"),
			Mchid:       core.String("1900009191"),
			Description: core.String("Image形象店-深圳腾大-QQ公仔"),
			OutTradeNo:  core.String("1217752501201407033233368018"),
			Attach:      core.String("自定义数据说明"),
			NotifyUrl:   core.String("https://www.weixin.qq.com/wxpay/pay.php"),
			Amount: &native.Amount{
				Total: core.Int64(100),
			},
		},
	)
	// 使用微信扫描 resp.code_url 对应的二维码，即可体验Native支付
	log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
}

// if err != nil {
// fmt.Println("load merchant private key error123")
// }
// 初始化微信支付
func InitWeChatPay() *core.Client {
	//mchPrivateKey, err := utils.LoadPrivateKeyWithPath("pkg/weixinpay/lss/apiclient_key.pem")
	//if err != nil {
	//	fmt.Println("load merchant private key error123")
	//}
	//mchPrivateKey, err := utils.LoadPrivateKey(ApiKey)
	ctx := context.Background()
	opts := []core.ClientOption{
		option.WithWechatPayAutoAuthCipher(MchID, MchCertificateSerialNumber, MchPrivateKey, MchAPIv3Key),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Fatalf("new wechat pay client err:%s", err)
	}

	return client
}

// 验证签名：
// 验证微信支付通知的签名
func VerifyWeChatPayNotification(signature, timestamp, nonce, body, apiKey string) bool {
	// 将参数和API密钥拼接成字符串
	signStr := timestamp + "\n" + nonce + "\n" + body + "\n"
	// 使用 API 密钥对拼接后的字符串进行 HMAC-SHA256 签名
	mac := hmac.New(sha256.New, []byte(apiKey))
	mac.Write([]byte(signStr))
	expectedSignature := hex.EncodeToString(mac.Sum(nil))
	// 比较微信支付通知中的签名和预期的签名是否一致
	return signature == expectedSignature
}
